/*
 * Created on 28/set/07
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package it.unibo.deis.lia.mmhc;

import it.unibo.deis.lia.networkInterface.*;
import it.unibo.deis.lia.mmhc.nip.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

//import java.net.*;
import java.util.*;

public class PeerConnectorGUI extends Thread implements ItemListener,
		ActionListener {

	private JFrame frame = null;
	private JTextField textFieldIpAddress = null;
	JCheckBox checkBoxRandom = null;
	// private JTextField textFieldExternal=null;
	// private GenericNetworkInterface internalInterface=null;
	// private GenericNetworkInterface externalInterface=null;
	private NetworkInterfaceProvider nip;

	public PeerConnectorGUI() throws Exception {
		nip = NetworkInterfaceProvider.getInstance();
	}

	public void run() {
		try {
			// JFrame
			frame = new InterfacesJFrame(this);
			frame.setTitle("PeerConnectorGUI");
			frame.pack();
			// frame.setSize(300,80);
			frame.setLocation(50, 50);
			frame.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void refresh() throws Exception {
		frame.setVisible(false);
		/* JFrame */frame = new InterfacesJFrame(this);
		frame.setTitle("PeerConnectorGUI");
		frame.pack();
		// frame.setSize(300,80);
		frame.setLocation(50, 50);
		frame.setVisible(true);
	}

	 
	 

	
	public void itemStateChanged(ItemEvent event) {
		JCheckBox source = (JCheckBox) (event.getSource());

		if (source.getText().equals("Random IP")) {
			if (event.getStateChange() == ItemEvent.SELECTED) {
				textFieldIpAddress.setEditable(false);
			} else if (event.getStateChange() == ItemEvent.DESELECTED) {
				textFieldIpAddress.setEditable(true);
			}
		} else {
			String interfacDescription = source.getText();

			try {
				String ipAddress = null;
				int rand = Math.round((float) Math.random() * 128);
				if (checkBoxRandom.isSelected() == false) {
					ipAddress = textFieldIpAddress.getText();
				} else {

					ipAddress = "192.168." + rand + ".1";
				}
				// System.out.println("source "+source);
				// System.out.println("interfacDescription "+interfacDescription);
				// System.out.println("ipAddress "+ipAddress);
				// System.out.println("event.getStateChange() "+event.getStateChange());
				GenericNetworkInterface interf = null;
				Vector<GenericNetworkInterface> interfacesIN = nip
						.getAvailableInterfaces();
				// System.out.println("PeerConnectorGUI interfacesIN: "+interfacesIN);
				for (int i = 0; i < interfacesIN.size() && interf == null; i++) {
					GenericNetworkInterface gni = interfacesIN.elementAt(i);
					// System.out.println("PeerConnectorGUI gni: "+gni);
					String description = gni.getDescription();
					// System.out.println("PeerConnectorGUI description: "+description);
					if (description.equals(interfacDescription)) {
						interf = gni;
						if (interf instanceof IEEE80211) {
							IEEE80211 ieee80211 = (IEEE80211) interf;
							if (event.getStateChange() == ItemEvent.SELECTED) {
								ieee80211.setConnectorRole("pippo" + rand,
										ipAddress, "./lib/");
								System.out
										.println("New remote connector IEEE 802.11: "
												+ ieee80211);
								textFieldIpAddress.setText(ipAddress);
							} else if (event.getStateChange() == ItemEvent.DESELECTED) {
								ieee80211.resetConnectorRole();
							}
						} else if (interf instanceof Bluetooth) {
							Bluetooth bluetooth = (Bluetooth) interf;
							if (event.getStateChange() == ItemEvent.SELECTED) {
								bluetooth.setConnectorRole(ipAddress, "./lib/");
								System.out
										.println("New remote connector Bluetooth: "
												+ bluetooth);
								textFieldIpAddress.setText(ipAddress);
							} else if (event.getStateChange() == ItemEvent.DESELECTED) {
								bluetooth.resetConnectorRole();
							}
						} else {
							throw new Exception("Interface not supported: "
									+ interf);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void actionPerformed(ActionEvent event) {
		try {
			JButton source = (JButton) (event.getSource());
			String text = source.getText();
			if (text.equals("refresh interfaces")) {
				System.out.println("PeerConnectorGUI refresh interfaces");
				refresh();
			} else {
				System.out.println("PeerConnectorGUI errror! " + text);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class InterfacesJFrame extends JFrame {

		private static final long serialVersionUID = 1L;

		public InterfacesJFrame(PeerConnectorGUI peerConnectorGUI)
				throws Exception {
			JFrame frame = this;
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			    frame.addWindowListener(new WindowAdapter() {
			        public void windowClosing(WindowEvent event) {
			        	try{
			        		Process k3 = Runtime.getRuntime().exec("sh dis.sh");
			        	
			    		k3.waitFor();
			    		k3.destroy();
			            }
			        	catch (Exception e) {
							// TODO: handle exception
						}
			        }
			    });
		 

			Container pane = frame.getContentPane();
			pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

			if (peerConnectorGUI.textFieldIpAddress == null) {
				peerConnectorGUI.textFieldIpAddress = new JTextField(
						"192.168.0.1");
				// textFieldIpAddress.setEnabled(false);
				peerConnectorGUI.textFieldIpAddress.setEditable(false);
			} else {
				boolean editable = peerConnectorGUI.textFieldIpAddress
						.isEditable();
				peerConnectorGUI.textFieldIpAddress = new JTextField(
						peerConnectorGUI.textFieldIpAddress.getText());
				peerConnectorGUI.textFieldIpAddress.setEditable(editable);
			}
			peerConnectorGUI.textFieldIpAddress
					.setAlignmentX(Component.CENTER_ALIGNMENT);
			pane.add(peerConnectorGUI.textFieldIpAddress);

			if (peerConnectorGUI.checkBoxRandom == null) {
				peerConnectorGUI.checkBoxRandom = new JCheckBox("Random IP",
						true);
			} else {
				peerConnectorGUI.checkBoxRandom = new JCheckBox("Random IP",
						peerConnectorGUI.checkBoxRandom.isSelected());
			}
			peerConnectorGUI.checkBoxRandom.addItemListener(peerConnectorGUI);
			peerConnectorGUI.checkBoxRandom
					.setAlignmentX(Component.CENTER_ALIGNMENT);
			pane.add(peerConnectorGUI.checkBoxRandom);

			JButton button1 = new JButton("refresh interfaces");
			button1.addActionListener(peerConnectorGUI);
			button1.setAlignmentX(Component.CENTER_ALIGNMENT);
			pane.add(button1);

			/**/// Vector<GenericNetworkInterface>
					// interfaces=GenericNetworkInterface.getInterfaces();
			Vector<GenericNetworkInterface> interfaces = nip
					.getAvailableInterfaces();
			for (int i = 0; i < interfaces.size(); i++) {
				GenericNetworkInterface gni = interfaces.elementAt(i);
				String description = gni.getDescription();

				// JLabel label = new JLabel(i+": "+description);
				// label.setAlignmentX(Component.CENTER_ALIGNMENT);
				// pane.add(label);
				if (gni instanceof IEEE80211) {
					IEEE80211 ieee80211 = (IEEE80211) gni;
					JCheckBox checkBox = new JCheckBox(description, ieee80211
							.isConnectorRole());
					checkBox.addItemListener(peerConnectorGUI);
					checkBox.setAlignmentX(Component.CENTER_ALIGNMENT);
					pane.add(checkBox);
				} else if (gni instanceof Bluetooth) {
					Bluetooth bluetooth = (Bluetooth) gni;
					JCheckBox checkBox = new JCheckBox(description, bluetooth
							.isConnectorRole());
					checkBox.addItemListener(peerConnectorGUI);
					checkBox.setAlignmentX(Component.CENTER_ALIGNMENT);
					pane.add(checkBox);
				} else {
					// throw new Exception("Interface not supported: "+gni);
					// System.out.println("Interface not supported: "+gni);
				}
			}/**/

			/*
			 * Enumeration<NetworkInterface>
			 * interfaces=java.net.NetworkInterface.getNetworkInterfaces();
			 * while(interfaces.hasMoreElements()){ NetworkInterface
			 * ni=interfaces.nextElement(); String
			 * description=ni.getDisplayName();
			 * 
			 * JLabel label = new JLabel(description);
			 * label.setAlignmentX(Component.CENTER_ALIGNMENT); pane.add(label);
			 * }/*
			 */

			/*
			 * JLabel label1 = new
			 * JLabel("===================================");
			 * label1.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(label1);
			 * 
			 * 
			 * 
			 * JButton button2 = new JButton("SET connector role");
			 * button2.addActionListener(peerConnectorGUI);
			 * button2.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(button2);
			 * 
			 * /textFieldInternal = new JTextField("internal interface");
			 * textFieldInternal.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(textFieldInternal); textFieldExternal = new
			 * JTextField("external interface");
			 * textFieldExternal.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(textFieldExternal);
			 * 
			 * 
			 * JLabel label2 = new
			 * JLabel("===================================");
			 * label2.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(label2);
			 * 
			 * 
			 * JButton button3 = new JButton("RESET connector role");
			 * button3.addActionListener(peerConnectorGUI);
			 * button3.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(button3);
			 * 
			 * JLabel internal = new JLabel("internal: "+internalInterface);
			 * internal.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(internal);
			 * 
			 * JLabel external = new JLabel("external: "+externalInterface);
			 * external.setAlignmentX(Component.CENTER_ALIGNMENT);
			 * pane.add(external);
			 */

			// frame.setSize(300,50);//.pack();
			// frame.setLocation(50, 50);
			// frame.setVisible(true);
		}
	}
}
